var express = require('express')
var db = require('./db.js')
var route = express.Router()
var bodyparse = require('body-parser')
var u = bodyparse.urlencoded({ express: false })

route.get('/get', async (req, res) => {
  var sql = ` select * from classify`
  let r = await db.doMysql(sql)
  res.send(db.backText(r))
})

route.get('/msbd', async (req, res) => {
  var { search, order, by, currentPage = 0, pageSize = 5 } = req.query
  var sql = ` select m.id,m.title,m.time,c.name as type from classify as c,msbd as m where m.cid=c.id`
  var sql_count = ` select count(*) as total from classify as c,msbd as m where m.cid=c.id`

  var num = currentPage * pageSize

  if (search) {
    sql += `  and m.title like '%${search}%'`
    sql_count += `   and m.title like '%${search}%'`
  }

  if (order) {
    sql += `    order by ${order} ${by}`
  }

  sql += `   limit ${num},${pageSize}`

  let r = await db.doMysql(sql)
  let r1 = await db.doMysql(sql_count)
  res.send(db.backText(r, r1))
})
// 新增
route.post('/addlist', u, async (req, res) => {
  var { name } = req.body
  console.log(name);
  var sql = `insert into classify (name) values("${name}")`
  let r = await db.doMysql(sql)
  res.send(db.backText(r))
})
// 修改
route.post('/updatelist', u, async (req, res) => {
  var sql = ` update classify set name=('${req.body.name}') where id='${req.body.id}'`

  let r = await db.doMysql(sql)
  res.send(db.backText(r))
})
// 删除
route.get('/delelist', async (req, res) => {
  var { id } = req.query
  // var sql=` delete from classify where id='${id}'`
  var sql = ` delete from classify where id in (${id})`
  let r = await db.doMysql(sql)
  res.send(db.backText(r))
})
module.exports = route